#!/bin/sh /etc/rc.common

START=99

tmp_dir="/tmp/radio"
tmp_volume="/tmp/radio/volume_level"
tmp_mute="/tmp/radio/tmp_mute"
playlist="/etc/config/web-radio2"

ls $tmp_dir &> /dev/null
if [ $? == 1 ]; then mkdir $tmp_dir; touch $tmp_volume; touch $tmp_mute; else touch $tmp_volume; touch $tmp_mute; fi

# save_volume
amixer -c 0 get 'Line Out' | sed -n 's/.*Front .*\: Playback \(.*\) \[.*%\].*/\1/p' | sed -n '1p' > $tmp_volume

killed() {
	killall -9 curl &> /dev/null &> /dev/null
	killall -9 wget &> /dev/null &> /dev/null
	killall -9 madplay &> /dev/null &> /dev/null
}

offvolume() {
	off_volume=$(sed -n '1p' $tmp_volume)
    while [ "$off_volume" -ge "0" ]; do
	amixer -c 0 -q set 'Line Out' $off_volume	# OFF: while -=1
	let "off_volume -= 1"
    done
#	amixer -c 0 -q set 'Line Out' 0	# выкл
	amixer -c 0 -q set "DAC" 100%-			# OFF
}

onvolume() {
	amixer -c 0 -q set "DAC" 100%			# ON
	i="0"
	on_volume=$(sed -n '1p' $tmp_volume)
    while [ "$i" -le "$on_volume" ]; do
	amixer -c 0 -q set 'Line Out' $i				# ON: while +=1
	let "i += 1"
    done
}

reload() {
	offvolume
	if [ $1 == "0" ]; then
		killed
	else
		killall -9 web-radio2 &> /dev/null > /dev/null
		killed
		web-radio2 -p $1 &
	fi
	onvolume
}

start() {
   offvolume
   pidof web-radio2 &> /dev/null
   if [ $? == 1 ]; then
	killall -9 web-radio2 &> /dev/null > /dev/null
	killed
	cat /tmp/play_name &> /dev/null
	if [ $? != 1 ]; then
		play_name=$(sed -n '1p' /tmp/play_name | sed -e "s/\"\|\'//g")
		t_href=$(sed -n '1p' /tmp/nl)
		numb=$(sed -n 's/#EXTINF:-\(.*\),"'$play_name'"/\1/p' $playlist)
		web-radio2 -p $numb &
#		web-radio2 -u $t_href -n $play_name -p $numb &
	else
		web-radio2 -p 1 &
	fi
   else
	killall -9 web-radio2 &> /dev/null > /dev/null
	killed
   fi
   onvolume
}

stop() {
	offvolume
	killall -9 web-radio2 &> /dev/null > /dev/null
	killed
	onvolume
}

restart() {
    if [ $1 == "0" ]; then	# mute
	read_tmp_mute=$(sed -n '1p' $tmp_mute )
	read_card=$(amixer -c 0 get 'Line Out' | sed -n 's/.*Front .*\: Playback \(.*\) \[.*%\].*/\1/p' | sed -n '1p')
	if [[ "$read_card" != "0" ]]; then
		amixer -c 0 get 'Line Out' | sed -n 's/.*Front .*\: Playback \(.*\) \[.*%\].*/\1/p' | sed -n '1p' > $tmp_mute
		amixer -c 0 -q set "Line Out" 0
	else
		amixer -c 0 get 'Line Out' | sed -n 's/.*Front .*\: Playback \(.*\) \[.*%\].*/\1/p' | sed -n '1p' > $tmp_mute
		amixer -c 0 -q set "Line Out" $read_tmp_mute
	fi
    else
	offvolume
	killall -9 web-radio2 &> /dev/null > /dev/null
	killed
	web-radio2 &
	onvolume
    fi
}

